/*
 * DataReader.cpp
 *
 *  Created on: Nov 17, 2010
 *      Author: dblyth
 */

#include <DataWriter.h>
#include <chid_1019.h>
#include <TBranch.h>
#include <iostream>
#include <sstream>
using namespace std;

DataWriter::DataWriter(int runNum) {
	crate = new TFile*[9];
	tree = new TTree*[9];
	dataBranch = new TBranch*[9];
	nFADCBranch = new TBranch*[9];
	pedestalBranch = new TBranch*[9];
	sumBranch = new TBranch*[9];
	for (int l = 0; l < 9; l++) {
		if (l == 8)
			nFADC[l] = 13;
		else
			nFADC[l] = 20;
		for (int i = 0; i < 20; i++) {
			for (int j = 0; j < 16; j++) {
				pedestal[l][i][j] = 0;
				sum[l][i][j] = 0;
				for (int k = 0; k < 48; k++)
					data[l][i][j][k] = 0;
			}
		}
		string fileName = "./";
		stringstream ssRun;
		ssRun.fill('0');
		ssRun.width(4);
		ssRun << runNum;
		stringstream ssCrate;
		ssCrate << l;
		fileName += "crate" + ssCrate.str() + "_run" + ssRun.str() + "_conv.root";
		crate[l] = new TFile(fileName.c_str(), "recreate");
		tree[l] = new TTree("EventTree", "EventTree");
		tree[l]->SetAutoSave(0xffff);
		dataBranch[l] = tree[l]->Branch("Data", &data[l], "Data[20][16][48]/I");
		nFADCBranch[l] = tree[l]->Branch("nFADC", &nFADC[l], "nFADC/I");
		pedestalBranch[l] = tree[l]->Branch("Pedestal", &pedestal[l], "Pedestal[20][16]/I");
		sumBranch[l] = tree[l]->Branch("Sum", &sum[l], "Sum[20][16]/D");
	}
}

DataWriter::~DataWriter() {
	for (int l = 0; l < 9; l++) {
		tree[l]->AutoSave("SaveSelf");
		crate[l]->Close();
	}
	delete[] crate;
	delete[] tree;
	delete[] dataBranch;
	delete[] nFADCBranch;
	delete[] pedestalBranch;
	delete[] sumBranch;
}

void DataWriter::writeData(unsigned int** din, double* sin) {
	for (int c = 0; c < 2760; c++) {
		if (din[c] != NULL) {
			int l = c / 320;
			int i = (c % 320) / 16;
			int j = (c % 320) % 16;
			pedestal[l][i][j] = din[c][48];
			sum[l][i][j] = sin[c];
			for (int k = 0; k < 48; k++)
				data[l][i][j][k] = din[c][k];
		}
	}
	for (int l = 0; l < 9; l++)
		tree[l]->Fill();
}
